package cn.fan.vertd.utils;

import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.client.Redis;
import io.vertx.redis.client.RedisClientType;
import io.vertx.redis.client.RedisConnection;
import io.vertx.redis.client.RedisOptions;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class RedisUtil {

    public static final Logger log = LogManager.getLogger();

    private static volatile RedisConnection redisConnection;

    public static void init(Vertx vertx, JsonObject conf) {
        JsonObject redisConf = conf.getJsonObject("redisServer");
        String redisLink = redisConf.getString("redis");
        RedisOptions redisOptions = new RedisOptions();
        redisOptions.setType(RedisClientType.STANDALONE)
                .addConnectionString(redisLink)
                .setMaxPoolSize(redisConf.getInteger("maxPoolSize"))
                .setMaxPoolWaiting(redisConf.getInteger("maxPoolWaiting"));
        if (redisConnection == null) {
            synchronized (RedisUtil.class) {
                if (redisConnection == null) {
                    Redis.createClient(vertx, redisOptions)
                            .connect()
                            .onSuccess(conn -> {
                                redisConnection = conn;
                                log.info("connect redis succeed");
                            })
                            .onFailure(event -> {
                                redisConnection = null;
                                log.error("connect redis failed, ", event);
                            });
                }
            }
        }
    }

    public static RedisConnection getRedisConnection() {
        return redisConnection;
    }
}
